import { find, isArray, get, first, map, intersection, isEqual, isEmpty } from "lodash";
import React from "react";
import PropTypes from "prop-types";
import Select from "antd/lib/select";
import TreeSelect from "antd/lib/tree-select";
import Radio from "antd/lib/radio";
import Checkbox from "antd/lib/checkbox";
import Enums from "@/services/enums";

const { SHOW_PARENT } = TreeSelect;
const { Option } = Select;

export default class EnumsParameterInput extends React.Component {
  static propTypes = {
    parameter: PropTypes.any, // eslint-disable-line react/forbid-prop-types
    value: PropTypes.any, // eslint-disable-line react/forbid-prop-types
    mode: PropTypes.oneOf(["default", "multiple"]),
    enumsValue: PropTypes.string,
    onSelect: PropTypes.func,
    className: PropTypes.string,
  };

  static defaultProps = {
    value: null,
    mode: "default",
    parameter: null,
    enumsValue: null,
    onSelect: () => {},
    className: "",
  };

  constructor(props) {
    super(props);
    this.state = {
      options: [],
      value: null,
      loading: false,
    };
  }

  componentDidMount() {
    this._loadOptions(this.props.enumsValue);
  }

  componentDidUpdate(prevProps) {
    if (this.props.enumsValue !== prevProps.enumsValue) {
      this._loadOptions(this.props.enumsValue);
    }
    if (this.props.value !== prevProps.value) {
      this.setValue(this.props.value);
    }
  }

  setValue(value) {
    const { options } = this.state;
    if (this.props.mode === "multiple") {
      value = isArray(value) ? value : [value];
      const optionValues = map(options, option => option.value);
      const validValues = intersection(value, optionValues);
      this.setState({ value: validValues });
      return validValues;
    }
    const found = find(options, option => option.value === this.props.value) !== undefined;
    value = found ? value : get(first(options), "value");
    this.setState({ value });
    return value;
  }

  async _loadOptions(enumsValue) {
    if (enumsValue && enumsValue !== this.state.enumsValue) {
      this.setState({ loading: true });

      const options = await this.props.parameter.loadDropdownValues();

      if (this.props.enumsValue === enumsValue) {
        this.setState({ options, loading: false }, () => {
          const updatedValue = this.setValue(this.props.value);
          if (!isEqual(updatedValue, this.props.value)) {
            this.props.onSelect(updatedValue);
          }
        });
      }
    }
  }

  render() {
    const { className, value, mode, onSelect, parameter, ...otherProps } = this.props;
    const { loading, options } = this.state;
    const showPortal = window.location.search.includes("show_portal") && localStorage.getItem('colorstyle_mode');
  
    if (Enums.itemsHasChildren(options))
      return (
        <span>
          <TreeSelect
            className={this.props.className}
            disabled={loading}
            loading={loading}
            treeData={options}
            placeholder="请选择"
            treeDefaultExpandAll
            // value={this.state.value}
            onChange={onSelect}
            dropdownMatchSelectWidth={false}
            treeCheckable={mode==='multiple' ? true : false}
            showCheckedStrategy={SHOW_PARENT}
            {...otherProps}
          />
        </span>
      );
    else if (parameter.tileDisplay && parameter.multiValuesOptions)
      return (
        <Radio.Button
          style={showPortal ? {backgroundColor: "#00000000", color: localStorage.getItem("colorstyle_color"), height: '35px'} : {height: '35px'}}
        >
        <Checkbox.Group
          defaultValue={ this.state.value instanceof Array && this.state.value}
          onChange={onSelect}
        >
          {map(options, ({ value, label })  => (<Checkbox value={value}>{String(label)}</Checkbox>))}
        </Checkbox.Group>
        </Radio.Button>
      );
    else if (parameter.tileDisplay)
      return (
        <Radio.Group
          buttonStyle="outline"        
          value={this.state.value}
          onChange={e => onSelect(e.target.value)}
        >
          {map(options, ({ value, label })  => (
            <Radio.Button
              style={showPortal ? {backgroundColor: "#00000000", color: localStorage.getItem("colorstyle_color"), height: '35px'} : {height: '35px'}}
              key={value}
              value={value}
            >
              {String(label)}
            </Radio.Button>
          ))}
        </Radio.Group>
      );
    else
      return (
        <span>
          <Select
          className={this.props.className}
          disabled={loading}
          loading={loading}
          mode={mode}
          showSearch
          optionFilterProp="label"
          value={this.state.value}
          onChange={onSelect}
          dropdownMatchSelectWidth={false}
          showArrow
          style={{ minWidth: 60 }}
          notFoundContent={isEmpty(options) ? "没有可选数据" : null}
          {...otherProps}>
          {options.map(option => (
            <Option key={option.value} value={option.value}>
              {option.label}
            </Option>
          ))}
          </Select>
        </span>
      );
  }
}
